//
//  WNTabBarVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/4.
//

import UIKit

class WNTabBarVC: UITabBarController, UITabBarControllerDelegate {
        
    
    lazy var libraryNav: WNBaseNaviVC = {
        let libraryVC = WNLibraryVC()
        let nav = WNBaseNaviVC.init(rootViewController: libraryVC)
        nav.tabBarItem = UITabBarItem(title: "書架", image: wn_tabIcon("tabbar_library"), selectedImage: wn_tabIcon("tabbar_library_sel"))
        return nav
    }()
    
    lazy var discoverNav: WNBaseNaviVC = {
        let discoverVC = WNDiscoverVC()
        let nav = WNBaseNaviVC.init(rootViewController: discoverVC)
        nav.tabBarItem = UITabBarItem(title: "發現", image: wn_tabIcon("tabbar_discover"), selectedImage: wn_tabIcon("tabbar_discover_sel"))
        return nav
    }()
    
    lazy var recommendNav: WNBaseNaviVC = {
        let recommendVC = WNRecommendVC()
        let nav = WNBaseNaviVC.init(rootViewController: recommendVC)
        nav.tabBarItem = UITabBarItem(title: "推薦", image: wn_tabIcon("tabbar_recommend"), selectedImage: wn_tabIcon("tabbar_recommend_sel"))
        return nav
    }()
    
    lazy var rankNav: WNBaseNaviVC = {
        let rankVC = WNRankVC()
        let nav = WNBaseNaviVC.init(rootViewController: rankVC)
        nav.tabBarItem = UITabBarItem(title: "排行榜", image: wn_tabIcon("tabbar_rank"), selectedImage: wn_tabIcon("tabbar_rank_sel"))
        return nav
    }()
    
    lazy var myNav: WNBaseNaviVC = {
        let myVC = WNMyVC()
        let nav = WNBaseNaviVC.init(rootViewController: myVC)
        nav.tabBarItem = UITabBarItem(title: "我的", image: wn_tabIcon("tabbar_me"), selectedImage: wn_tabIcon("tabbar_me_sel"))
        return nav
    }()
    
    var libRecModel: BookDetailModel? {
        didSet {
            if let m = libRecModel {
                showLibRec(self, m)
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        tabBar.shadowImage = UIImage()
        tabBar.backgroundImage = UIImage()
        tabBar.backgroundColor = .white
        tabBar.tintColor = .init(named: "red_FE95B4")
        tabBar.unselectedItemTintColor = .init(named: "gray_CECECE")
        tabBarItem.setTitleTextAttributes([NSAttributedString.Key.font: UIFont.wn_font(name: .bold, size: 14)], for: .normal)
        tabBarItem.setTitleTextAttributes([NSAttributedString.Key.font: UIFont.wn_font(name: .bold, size: 14)], for: .selected)
        viewControllers = [libraryNav, discoverNav, myNav]
        delegate = self
        selectedIndex = 1
        tabBar.wn_cornerWithBorder(0, 0, .white, 1, .init(white: 0, alpha: 0.1), .init(width: 0, height: 1), 5)
        tabBar.layer.masksToBounds = false
        WNBuriedManager.shared.startEvents("home page")
        appDelegate.settingAndSDKConfig()
        if let lica = appDelegate.wn_application {
            appDelegate.threeConfig(lica, didFinishLaunchingWithOptions: appDelegate.wn_launchOptions)
        }
    }
    
    func handleConfig() {
        if getReadConfig().count == 0 {
            saveReadConfig(["brightness": Float(UIScreen.main.brightness), "size": 16, "space": 5.0, "bgColor": "FFFFFF", "font": "regular", "flip": "Page"])
        }
        if getKeyUUId().isEmpty {
            setKeyUUId(getUUID())
        }
        if getTapAD() {
            saveTapAD(false)
            let adModel = ADModel.deserialize(from: getAdJson())
            saveAdJson([:])
            wn_pushBookVC(adModel?.bookId ?? "")
        }else {
            getLibADRequest()
        }
        getOpenADRequest()
        saveIsDeeplink(false)
        
        WNLibRecView.shared.recClosure = { [weak self] in
            self?.versionRequest()
        }
    }
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> (Bool) {
        let nav = viewController as! UINavigationController
        let _ : UIViewController = nav.viewControllers[0]
        return true
    }
    
    func wn_tabIcon(_ iconName: String, _ size: CGSize = CGSize(width: 20, height: 20)) -> UIImage {
        return (UIImage(named: iconName)?.wn_resized(newSize: size) as AnyObject).withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
    }
}

extension WNTabBarVC {
    
    func getLibADRequest() {
        if !getIsDeeplink() {
            provider_recommend.rx.request(.openAdvert(2))
                .asObservable().mapModel(BaseModel<[BookDetailModel]>.self)
                .subscribe(onNext: { [weak self] (model) in
                    guard model.code == 0 else {
                        return
                    }
                    if let arr = model.data, arr.count > 0 {
                        self?.libRecModel = arr[Int(arc4random())%arr.count]
                    }else {
                        self?.versionRequest()
                    }
                }, onError: { (error) in
                }).disposed(by: rx.disposeBag)
        }
    }
    
    func versionRequest() {
        if !getUpgradeClose() {
            provider_setting.rx.request(.versionUpgrade)
                .asObservable().mapModel(BaseModel<VersionModel>.self)
                .subscribe(onNext: { (model) in
                    guard model.code == 0 else {
                        return
                    }
                    if let m = model.data {
                        if wn_toInt(m.versions?.replacingOccurrences(of: ".", with: "")) > wn_toInt(getAPPVersion().replacingOccurrences(of: ".", with: "")) {
                            showVersion(m)
                        }
                    }
                }, onError: { (error) in
                }).disposed(by: rx.disposeBag)
        }
    }
    
    func getOpenADRequest() {
        provider_recommend.rx.request(.openAdvert(1))
            .asObservable().mapModel(BaseModel<[ADModel]>.self)
            .subscribe(onNext: { (model) in
                guard model.code == 0 else {
                    return
                }
                if let arr = model.data, arr.count > 0 {
                    saveAdJson((arr[Int(arc4random())%arr.count].toJSON())!)
                }
            }, onError: { (error) in
            }).disposed(by: rx.disposeBag)
    }
}
